{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2d4c0469-5931-4422-8394-4e628b951fce",
   "metadata": {},
   "source": [
    "### 张量的保存和加载\n",
    "- 模型参数一般是张量形式\n",
    "- 对于单个张量："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "10e31e91-9127-4eac-9c5d-5c552d8673dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bd159a3a-e280-4e90-a6b9-c565da36f60f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0.3729, 0.7582, 0.4932, 0.0963, 0.0974, 0.1193])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = torch.rand(6)\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "38841a15-5438-4805-86a5-5422e14138fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.save(a, \"model/tensor_a\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ef6bda4e-cc66-4363-9e0e-32df7c421831",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\CHX\\AppData\\Local\\Temp\\ipykernel_20268\\18023226.py:1: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  torch.load(\"model/tensor_a\")\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "tensor([0.3729, 0.7582, 0.4932, 0.0963, 0.0974, 0.1193])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.load(\"model/tensor_a\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "746b58fb-4f77-4efa-b45b-8018d1d67c05",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[tensor([0.4225, 0.5000, 0.2504, 0.0053, 0.5484, 0.5194]),\n",
       " tensor([0.9997, 0.7678, 0.2066, 0.8709, 0.7404, 0.9633]),\n",
       " tensor([0.3282, 0.3457, 0.5172, 0.4588, 0.5328, 0.2432])]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 保存张量列表\n",
    "a = torch.rand(6)\n",
    "b = torch.rand(6)\n",
    "c = torch.rand(6)\n",
    "[a, b, c]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "dcb54a7a-656b-4fd8-833c-4f0e5454c0d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.save([a, b, c], \"model/tensor_abc\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "15df09f5-4beb-4616-b378-aa25570d1910",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\CHX\\AppData\\Local\\Temp\\ipykernel_20268\\3520973659.py:1: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  torch.load(\"model/tensor_abc\")\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[tensor([0.4225, 0.5000, 0.2504, 0.0053, 0.5484, 0.5194]),\n",
       " tensor([0.9997, 0.7678, 0.2066, 0.8709, 0.7404, 0.9633]),\n",
       " tensor([0.3282, 0.3457, 0.5172, 0.4588, 0.5328, 0.2432])]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.load(\"model/tensor_abc\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "bc953d70-ce65-4351-bf69-762ffa2369e0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': tensor([0.4225, 0.5000, 0.2504, 0.0053, 0.5484, 0.5194]),\n",
       " 'b': tensor([0.9997, 0.7678, 0.2066, 0.8709, 0.7404, 0.9633]),\n",
       " 'c': tensor([0.3282, 0.3457, 0.5172, 0.4588, 0.5328, 0.2432])}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tensor_dict = {\n",
    "    \"a\": a,\n",
    "    \"b\": b,\n",
    "    \"c\": c\n",
    "              }\n",
    "tensor_dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "20999ca6-8bcf-4eef-8747-9c6bded51048",
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.save(tensor_dict, \"model/tensor_dict\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "80f51cbf-528f-4f16-87f5-0f1ec03fe823",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\CHX\\AppData\\Local\\Temp\\ipykernel_20268\\473931919.py:1: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  torch.load(\"model/tensor_dict\")\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'a': tensor([0.4225, 0.5000, 0.2504, 0.0053, 0.5484, 0.5194]),\n",
       " 'b': tensor([0.9997, 0.7678, 0.2066, 0.8709, 0.7404, 0.9633]),\n",
       " 'c': tensor([0.3282, 0.3457, 0.5172, 0.4588, 0.5328, 0.2432])}"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.load(\"model/tensor_dict\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a61f88d-6df6-4b31-aacd-697c5e982359",
   "metadata": {},
   "source": [
    "### 模型参数保存"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f337b51a-c83f-468c-9eda-77e96cd2a0cb",
   "metadata": {},
   "source": [
    "#### 方法一：保存模型参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "97975c1f-433c-42e0-b7f5-11f448880db8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# torch.save(model.state_dict(), \"model/mlp_state_dict.pth\") # 保存的是模型参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "0c6da719-b862-4961-b904-302f56797669",
   "metadata": {},
   "outputs": [],
   "source": [
    "# mlp_state_dict = torch.load(\"model/mlp_state_dict.pth\")\n",
    "# model_load = MLP(input_size, hidden_size, num_classes)\n",
    "# model_load.load(mlp_state_dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62a20e89-83b6-4708-96dc-4b59f33ff7d4",
   "metadata": {},
   "source": [
    "#### 方法二：保存整个模型（不推荐）\n",
    "在保存模型的时候会把模型结构定义 文件路径记录下来，加载的时候直接根据文件路径加载参数。如果文件路径被修改就会报错"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "0dd7a77a-12e5-4932-a57f-7ce93f51dd8f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# torch.save(model, \"model/mlp_model.pth\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "21408aaa-5b1d-4d3e-a7ed-046bd3f8759a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# mlp_load = torch.load(\"model/mlp_model.pth\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2403260f-3ae0-4cb3-ae1c-418db870ca58",
   "metadata": {},
   "source": [
    "### 方法三：checkpoint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "d6fda465-1530-497c-b2df-32e7d3bd8b04",
   "metadata": {},
   "outputs": [],
   "source": [
    "# torch.save({\n",
    "#     'epoch': epoch,\n",
    "#     'model_state_dict': model.state_dict(),\n",
    "#     'optimizer_state_dict': optimizer.state_dict(),\n",
    "#     'loss': loss,\n",
    "#     # ......\n",
    "# }, PATH)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "1f18edda-a721-47e2-a2fc-be606b134782",
   "metadata": {},
   "outputs": [],
   "source": [
    "# model = TheModelClass(*args, **kwargs)\n",
    "# optimizer = TheOptimizerClass(*args, **kwargs)\n",
    "\n",
    "# checkpoint = torch.load(PATH)\n",
    "# model.load_state_dict(checkpoint['model_state_dict'])\n",
    "# optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n",
    "# epoch = checkpoint['epoch']\n",
    "# loss = checkpoint['loss']\n",
    "\n",
    "# model.eval()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.21"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
